package test;

public class WaitInterruptExample {

    public synchronized void waitForSignal() throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + " 等待信号...");
        // 调用wait()方法使线程进入等待状态
        wait();
        // 等待结束后打印一条信息
        System.out.println(Thread.currentThread().getName() + " 收到信号！");
    }

    public synchronized void signal() {
        // 调用notify()方法唤醒一个等待的线程
        notify();
    }

    public static void main(String[] args) throws InterruptedException {
        // 创建一个WaitInterruptExample实例
        WaitInterruptExample example = new WaitInterruptExample();
        // 创建一个等待线程
        Thread waitingThread = new Thread(() -> {
            try {
                example.waitForSignal();
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println(Thread.currentThread().getName() + " 被中断了！");
            }
        }, "等待线程");
        // 启动等待线程
        waitingThread.start();
        // 睡眠1秒钟
        Thread.sleep(1000);
        // 中断等待线程
        waitingThread.interrupt();
    }
}
